package baiqi.sishen.community.advice;

import baiqi.sishen.community.dto.ResultDTO;
import baiqi.sishen.community.execption.CustomizeException;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author 兕神
 * @version 1.0
 * DateTime: 2023/5/1
 */
@ControllerAdvice(annotations = {Controller.class, RestController.class})
public class CustomizeExceptionHandler {

    //自定义异常处理
    @ExceptionHandler(CustomizeException.class)
    public ModelAndView exceptionHandler(
            Throwable e, Model model,
            HttpServletRequest request,
            HttpServletResponse response) {
        String contentType = request.getContentType();
        if (contentType.equals("application/json")) {
            ResultDTO resultDTO = ResultDTO.error((CustomizeException) e);

            try {
                response.setStatus(200);
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                PrintWriter writer = response.getWriter();
                writer.write(JSON.toJSONString(resultDTO));
                writer.close();
            } catch (IOException ioException) {
            }
        }else{
            model.addAttribute("message", e.getMessage());
        }
        return new ModelAndView("error");
    }

    @ExceptionHandler(Exception.class)
    public ModelAndView exceptionHandler2(Throwable e, Model model) {
        model.addAttribute("message", "服务器匆忙，稍后再尝试一下呗");
        return new ModelAndView("error");
    }
}
